package com.example.shop_2211.detail

import android.R.attr
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup.LayoutParams
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.example.base.mvvm.BaseActivity
import com.example.shop_2211.R
import com.example.shop_2211.adapter.ReplyAdapter
import com.example.shop_2211.databinding.ActivityDetailBinding
import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.BarcodeEncoder
import com.journeyapps.barcodescanner.CaptureActivity
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.youth.banner.loader.ImageLoader


@Route(path = "/app/DetailActivity")
class DetailActivity : BaseActivity<ActivityDetailBinding,DetailViewModel>() {
    @Autowired
    @JvmField
    var goodsId = 1//正常应该给0，为了防止传值失败时，导致数据没有，页面不能正确回显
    var attrId = ""//属性id
    var imgurl = ""//动画图片
    lateinit var dialog:AlertDialog

    val list = mutableListOf<String>()//存放轮播图图片

    lateinit var replyAdapter: ReplyAdapter
   @SuppressLint("MissingInflatedId")
   override fun initView() {
       ARouter.getInstance().inject(this)
       viewModel.detail(goodsId)
       binding.addCart.setOnClickListener {
           viewModel.addCar(1,attrId,goodsId)
       }
       binding.ivBack.setOnClickListener {
           finish()
       }
       //点击购物车图标，可以跳转到购物车页面
       binding.tvCar.setOnClickListener {
           //跳转到主页的第几个fragment中
           ARouter.getInstance().build("/app/MainActivity").withInt("index",2).navigation()
       }
       binding.ivShare.setOnClickListener {
           //弹出一个自定义框，显示二维码，点击确定实现分享
           val view = LayoutInflater.from(this).inflate(R.layout.dialog_diy, null)
           //二维码
           val bitmap = BarcodeEncoder().encodeBitmap(
               binding.tvName.text.toString(),
               BarcodeFormat.QR_CODE,
               100,
               100
           )
           view.findViewById<ImageView>(R.id.iv).setImageBitmap(bitmap)
           view.findViewById<Button>(R.id.yes).setOnClickListener {
               //实现分享功能
               val image: UMImage = UMImage(this, bitmap) //bitmap文件
               ShareAction(this).withText("hello").withMedia(image)
                   .setCallback(object:UMShareListener{
                       override fun onStart(p0: SHARE_MEDIA?) {
                       }

                       override fun onResult(p0: SHARE_MEDIA?) {
                       }

                       override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                           ToastUtils.showLong(p1?.message)
                       }

                       override fun onCancel(p0: SHARE_MEDIA?) {
                       }
                   })
                   .open()
               dialog.dismiss()//关闭对话
           }
           view.findViewById<Button>(R.id.no).setOnClickListener {
               dialog.dismiss()
           }
            dialog= AlertDialog.Builder(this)
               .setTitle("提示")
               .setView(view)
               .create()
           dialog.show()
       }
       binding.tvKefu.setOnClickListener {
           val intent = Intent(this,CaptureActivity::class.java)
           startActivityForResult(intent,200)
       }

       replyAdapter = ReplyAdapter()
       binding.rvComment.adapter = replyAdapter
       binding.rvComment.layoutManager = LinearLayoutManager(this)
       viewModel.reply(goodsId,10,1,"0")

       viewModel.comment()

    }

    override fun initData() {
        viewModel.commentSuccess.observe(this){
            Log.d("sss", "initData:${it.data} ")
        }
        viewModel.detailSuccess.observe(this){
            if(it.code==200){
                binding.info = it.data.productInfo
                attrId = it.data.productAttr[0].id.toString()
                imgurl = it.data.productInfo.image
                Log.d("sss", "initData: $attrId")
                list.add(it.data.productInfo.image)
                list.add(it.data.productInfo.image)
                binding.banner.setImages(list)
                    .setImageLoader(object :ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            if (context != null&&imageView!=null) {
                                Glide.with(context).load(path).into(imageView)
                            }
                        }
                    })
                    .start()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.detailFail.observe(this){
            ToastUtils.showLong(it)
        }
        viewModel.addSuccess.observe(this){
            ToastUtils.showLong(it.message)
            //添加购物车成功，展示动画效果
            if(it.code==200){
                val imageview = ImageView(this)
                val layoutParams = LayoutParams(200, 200)
                imageview.layoutParams = layoutParams
                Glide.with(this).load(imgurl).into(imageview)
                binding.cl.addView(imageview)
                //获取屏幕宽高
                val width = windowManager.defaultDisplay.width.toFloat()
                val height = windowManager.defaultDisplay.height.toFloat()
                val translationX = ObjectAnimator.ofFloat(imageview, "translationX", 0f, width)
                val translationY = ObjectAnimator.ofFloat(imageview, "translationY", 0f, height)
                val set = AnimatorSet()
                set.play(translationX).with(translationY)
                set.duration = 2000
                set.start()
                set.addListener(object:Animator.AnimatorListener{
                    override fun onAnimationStart(animation: Animator) {
                    }

                    override fun onAnimationEnd(animation: Animator) {
                        binding.cl.removeView(imageview)
                    }

                    override fun onAnimationCancel(animation: Animator) {
                    }

                    override fun onAnimationRepeat(animation: Animator) {
                    }

                })

            }
        }
        viewModel.addFail.observe(this){
            ToastUtils.showLong(it)
        }
        viewModel.replySuccess.observe(this){
            if(it.code==200){
                replyAdapter.data.clear()
                replyAdapter.data.addAll(it.data.list)
                replyAdapter.notifyDataSetChanged()
                if(it.data.total==0){
                    binding.noComment.isVisible = true
                }
            }
        }
    }

    override fun getViewModel(): Class<DetailViewModel> = DetailViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_detail

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==200&&resultCode== RESULT_OK){
            val string = data?.extras?.getString("result_string")
            Log.d("sss", "onActivityResult: $string")
        }
    }

}